#include "Stack.h"

void stackInit(Stack* pst)
{
	assert(pst);

	pst->data = NULL;
	pst->capacity = pst->size = 0;
}

void stackDesTroy(Stack* pst)
{
	assert(pst);

	free(pst->data);
	pst->data = NULL;
	pst->capacity = pst->size = 0;
}

void checkCapacity(Stack* pst)
{
	assert(pst);

	if (pst->capacity == pst->size)
	{
		int newcapacity = pst->capacity == 0 ? 2 : 2 * pst->capacity;
		StackDataType* node = (StackDataType*)realloc(pst->data, newcapacity * sizeof(StackDataType));
		if (node == NULL)
		{
			perror("malloc falil");
			exit(EXIT_FAILURE);
		}

		pst->data = node;
		pst->capacity = newcapacity;
	}
}

int stackIsEmpty(Stack* pst)
{
	assert(pst);

	return pst->size == 0 ? 1 : 0;
}

void stackPush(Stack* pst, StackDataType data)
{
	assert(pst);

	checkCapacity(pst);

	pst->data[pst->size] = data;
	pst->size++;
}

void stackPop(Stack* pst)
{
	assert(pst);
	assert(pst->size > 0);

	pst->size--;
}

StackDataType stackTop(Stack* pst)
{
	assert(pst);
	assert(pst->size > 0);

	return pst->data[pst->size-1];
}

int stackSize(Stack* pst)
{
	assert(pst);

	return pst->size;
}
